﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace KsMusic.common
{
    public class MyHttpClient
    {
        public string methodUrl = string.Empty;
        public string postStr = null;
        public string path = string.Empty;

        public MyHttpClient(String methodUrl)
        {
            this.methodUrl = methodUrl;
        }

        public MyHttpClient(String methodUrl, String postStr)
        {
            ///this.methodUrl = ConfigurationManager.AppSettings["ApiFrontEnd"];///http://192.168.1.6:8098/Signin/LoginApi  
            ///this.postStr = postStr;  

            this.methodUrl = methodUrl;
            this.postStr = postStr;
        }

        /// <summary>
        /// 下载
        /// </summary>
        /// <param name="url"></param>
        /// <param name="path"></param>
        /// <param name="download"></param>
        public MyHttpClient(string url, string path, bool download)
        {
            this.methodUrl = url;
            this.path = path;
        }

        /// <summary>  
        /// GET Method  
        /// </summary>  
        /// <returns></returns>  
        public String ExecuteGet()
        {
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(this.methodUrl);
            myRequest.Method = "GET";

            HttpWebResponse myResponse = null;
            try
            {
                myResponse = (HttpWebResponse)myRequest.GetResponse();
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                string content = reader.ReadToEnd();
                return content;
            }
            //异常请求  
            catch (WebException e)
            {
                myResponse = (HttpWebResponse)e.Response;
                using (Stream errData = myResponse.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(errData))
                    {
                        string text = reader.ReadToEnd();

                        return text;
                    }
                }
            }
        }

        /// <summary>  
        /// POST Method  
        /// </summary>  
        /// <returns></returns>  
        public string ExecutePost()
        {
            string content = string.Empty;

            Random rd = new Random();
            int rd_i = rd.Next();
            String nonce = Convert.ToString(rd_i);
            String timestamp = Convert.ToString(StringUtils.ConvertDateTimeInt(DateTime.Now));
            //String signature = GetHash(this.appSecret + nonce + timestamp);

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.methodUrl);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                //request.ContentType = "application/json";  
                request.Headers.Add("Nonce", nonce);
                request.Headers.Add("Timestamp", Convert.ToString(StringUtils.ConvertDateTimeInt(DateTime.Now)));
                //request.Headers.Add("Signature", signature);
                request.ReadWriteTimeout = 30 * 1000;

                byte[] data = Encoding.UTF8.GetBytes(postStr);
                request.ContentLength = data.Length;

                Stream myRequestStream = request.GetRequestStream();

                myRequestStream.Write(data, 0, data.Length);
                myRequestStream.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                content = myStreamReader.ReadToEnd();
                myStreamReader.Close();
            }
            catch (Exception ex)
            {
            }
            return content;
        }

        /// <summary>
        /// Http下载文件
        /// </summary>
        public string HttpDownloadFile()
        {
            // 设置参数
            HttpWebRequest request = WebRequest.Create(this.methodUrl) as HttpWebRequest;

            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream responseStream = response.GetResponseStream();
            //创建本地文件写入流
            Stream stream = new FileStream(path, FileMode.Create);
            byte[] bArr = new byte[1024];
            int size = responseStream.Read(bArr, 0, (int)bArr.Length);
            while (size > 0)
            {
                stream.Write(bArr, 0, size);
                size = responseStream.Read(bArr, 0, (int)bArr.Length);
            }

            stream.Close();
            responseStream.Close();
            return path;
        }
    }
}
